package dk
{
	import flash.events.*;
	import flash.filesystem.*;
	import flash.media.Camera;
	import flash.media.Video;
	import flash.net.LocalConnection;
	import flash.utils.Timer;
			
	public class MotionDetect
	{
		private var vid:Video;
		private var delayTimer:Number = 100;
		private var countLog:int = 0;
		private var conn:LocalConnection;
		
		[Bindable]
		public var camName:String;
		
		[Bindable]
		public var rfidString:String;
		
		private var cam:Camera;
		private var timer:Timer;
		private var collTimer:Timer;
		
		//camera's properties
		private var camW:int=		320;
		private var camH:int=		240;
		private var camF:Number=	24;
		[Bindable]
		private var camT:Number=2000;
		[Bindable]
		private var camM:int = 20;
		
		public var logEntry:String = "";
		public var logString:String = "";
		
		public function MotionDetect()
		{
			//trace("Motion Dectect constructor()");
			//cam = Camera.getCamera();
			trace(this+"Constructed!");
			
			//check
			startChecking();
			
			//connect to Local Connection
			//InitConn();
			
		}
		
		private function startChecking():void
		{
			if (timer==null)
			{
				timer = new Timer(delayTimer);
				timer.addEventListener(TimerEvent.TIMER, timerEventHandler);
			}
			timer.start(); 
		}
		
		private function stopChecking():void 
		{
			if(timer != null && timer.running) 
			{
				timer.stop();
			}
		}
		
		private function timerEventHandler(event:TimerEvent):void
		{
			cameraCheck();
		}
		
		private function cameraCheck():void
		{
			if (camName!=null)
			{
				trace(this+"Camera name= "+camName);
				//camera = new Camera();
				cam = Camera.getCamera(camName);
			}
				
			//check have camera or not
			if (cam != null) 
			{
				trace(this+"Found a cam!");
				//configure camera
				cam.setMode(camW,camH,camF);
				cam.setMotionLevel(camM, camT);
				trace(this+"$: configure camera DONE!");
				
				//stop checking camera
				stopChecking();
				
				//start Motion Detecting
				startDetecting();
            } 
            else 
            {
                trace(this+"Checking camera...");
            }
        }
        
        public function startDetecting():void
		{
			trace(this+"startDetecting()");
			if (cam != null) {
                cam.addEventListener(ActivityEvent.ACTIVITY, activityHandler);
                vid = new Video(cam.width, cam.height);
                vid.attachCamera(cam);
                //addChild(vid);
            } else {
                trace(this+"You need a camera.");
                startChecking();
            }
		}
		
        public function activityHandler(event:ActivityEvent):void {
            //trace("activityHandler: " + event);
            if (event.activating)
            {
            	//trace("Motion detected!!! Motion: "+cam.activityLevel);
            }
            else
            {
            	//trace("no more motioning.");
            }
		}
		
		public function startCollectMotionData():void
		{
			trace(this);
			if (collTimer==null)
			{
				collTimer = new Timer(100, 200);
				collTimer.addEventListener(TimerEvent.TIMER, collTimerEventHandler);
			}
			collTimer.start(); 
		}
		
		private function collTimerEventHandler(event:TimerEvent):void
		{
			collectMotionData();
		}
		
		private function collectMotionData():void
		{
			trace(this);
			var thisTime:Date = new Date();
			var timeString:String = thisTime.hours+":"+thisTime.minutes+":"+thisTime.seconds;
			var filePath:String = "C:/dataMotion/";
			//filePath += thisTime.hours+"_"+thisTime.minutes+"_"+thisTime.seconds+"_"+rfidString;
			filePath += thisTime.fullYear.toString()+thisTime.month.toString()+thisTime.date.toString();
			filePath += ".txt";
			trace("filePath: "+filePath);
			logEntry= timeString+" "+cam.activityLevel;
			trace(logEntry);
			logString += logEntry;
			if (countLog==0){logString += " "+rfidString;}
			logString += "\r\n";
			countLog++;
			if (countLog==200){
				var fs:FileStream = new FileStream();
				var file:File = new File(filePath);
				var fileMode : String = FileMode.APPEND;
				fs.open(file, fileMode);
				fs.writeUTFBytes(logString);
				fs.close();
				countLog=0;
				logString = "";
				collTimer=null;
			}
		}
		
		
		//for receiving RFID connection from flash-vb

			/* public function InitConn():void
			{
				conn= new LocalConnection();
				conn.client = this;
				conn.allowDomain('*');
				try {
					conn.connect("taskConnection");
					trace("connect ok!");
				} catch (error:ArgumentError) {
					trace("Can't connect.");
				}
			}

			public function localconnectionHandler(msg:String):void 
			{
				trace(this+"localconnectionHandler");
				if (msg!=null)
				{
					if (msg!="0")
					{
						rfidString = msg;
						trace("rfidString: "+rfidString);
						startCollectMotionData();
					}
					else
					{
						//stopCollectMotionData();
					}
				}
			} */


	}
}